<template>
  <lay-layer type="drawer" v-model="visible" title="认领" class="layer_center">
    <div class="from_box">
      <lay-form :model="validateModel" ref="layFormRef" required >
        <lay-form-item label="检测时间" >
          <lay-date-picker style="width: 100%;" 
            placeholder="请选择检测时间" 
            v-model="validateModel.detectionTime" 
            simple 
            type="date">
          </lay-date-picker>
        </lay-form-item>
        <!-- 认领时新增检测时间detectionTime -->
        <lay-form-item label="数量" prop="numberofTests">
          <lay-input
            placeholder="请输入数量"
            v-model="validateModel.numberofTests"
          ></lay-input>
        </lay-form-item>
        <lay-form-item label="单位" >
          <lay-input disabled v-model="validateModel.unit"></lay-input>
        </lay-form-item>

        <lay-form-item label="检测人员">
          <lay-select
            v-model="validateModel.testerId"
            :allow-clear="true"
            :multiple="true"
            :show-search="true"
            placeholder="选择检测人员"
          >
            <lay-select-option
              v-for="(item, index) in userList"
              :key="index"
              :value="item"
              :label="item"
            ></lay-select-option>
          </lay-select>
        </lay-form-item>
        <lay-form-item label="设备">
          <div>
            <div>已选设备</div>
            <!-- sbTag -->
            <template v-for="(item, index) of layTagItem" :key="`tag-${index}`">
              <lay-tag class="tagSb" closable @close="removerTag(index)">
                {{systemType == '1' ? item.deviceNo : item.managementNo}} + {{' —— ' + item.deviceName + ' —— ' + item.model }}
              </lay-tag>
            </template>
          </div>
          <!-- @search="getShebMsg" -->
          <!-- @change="changeSelectTag" -->
          <lay-select
            v-model="validateModel.deviceNameIds"
            :allow-clear="true"
            :multiple="true"
            :show-search="true"
            @change="changeSelectTag"
            placeholder="选择设备"
          >
            <div v-if=" systemType == '1' ">
              <lay-select-option
                v-for="(item, index) in shebeiList"
                :key="index"
                :value="item.deviceId"
                :label=" item.deviceNo + ' —— ' + item.deviceName + ' —— ' + item.model"
              >
              </lay-select-option>
            </div>
            <div v-else>
              <lay-select-option
                v-for="(item, index) in shebeiList"
                :key="index"
                :value="item.deviceId"
                :label=" item.managementNo + ' —— ' + item.deviceName + ' —— ' + item.model"
              >
              </lay-select-option>
            </div>
            
          </lay-select>
        </lay-form-item>
        <lay-form-item>
          <lay-button @click="validate" type="primary">提交</lay-button>
          <lay-button @click="clearValidate">取消</lay-button>
        </lay-form-item>
      </lay-form>
    </div>
  </lay-layer>
</template>

<script lang="ts">
import { ref, reactive, toRefs, onMounted } from "vue";
import { layer } from "@layui/layer-vue";
import {
  GetTestItemInfo,
  DoClaim,
  GetDeviceInfos,
  GetUserNameList,
} from "../../../../api/module/user";
export default {
  props: [],
  setup(props: any, event: any) {
    

    const GetTestItemInfos = async (str: string) => {
      const res = await GetTestItemInfo({
        pageIndex: 1,
        pagePerCount: 1000,
        condition: str,
      });
      if (res.code === 200) {
        if (res.data.datas[0].unit && res.data.datas[0].unit.length) {
          data.validateModel.unit = res.data.datas[0].unit;
        } else {
           data.validateModel.unit = res.data.datas[0].testItemName;
        }
      }
    };

    const getShebeList = async () => {
      const res: any = await GetDeviceInfos({
        pageIndex: 1,
        pagePerCount: 2500,
        condition: data.msg,
      });

      if (res.code == 200) {
        data.shebeiList = res.data.datas;
      }
    };

    const getUserList = async (obj: any) => {
      const res: any = await GetUserNameList({
        pageIndex: 1,
        pagePerCount: 1000,
        condition: {},
      });
      if (res.code === 200) {
        data.userList = [...res.data.datas];
      }
    };

    const data = reactive({
      detectionId: 0,
      shebeiList: [] as any,
      userList: [] as any,
      msg: "",
      sbTag: [] as any,
      validateModel: {
        testerId: [] as any,
        deviceNameIds: [] as any,
      } as any,
      layTagItem: [] as any,
      systemType: sessionStorage.getItem("systemType"),
    });

    const visible = ref(false);

    let httpUrl: any = ref([]);
    const open = (item: any) => {
      // data.layTagItem = [];
      data.sbTag = [];
       console.log("validateModel.deviceNameIds", data.validateModel.deviceNameIds);
      let url: any = sessionStorage.getItem("httpUrl");
      httpUrl.value = JSON.parse(url);
      // for (let key in data.validateModel) {
      //   delete data.validateModel[key];
      // }
      // data.validateModel.testerId = [];
      // data.validateModel.deviceNameIds = [];
      data.validateModel.detectionTime = '';
      data.validateModel.numberofTests = '';
      data.detectionId = item.detectionId;

      if (httpUrl.value.includes("/Setting/GetDeviceInfos")) {
        getShebeList();
      }
      if (httpUrl.value.includes("/Setting/GetUserNameList")) {
        getUserList(item.tiem);
      }
      if (httpUrl.value.includes("/Setting/GetTestItemInfo")) {
        GetTestItemInfos(item.testItems);
      }
      visible.value = true;
    };

    const layFormRef: any = ref(null);
    // 校验
    const validate = function () {
      layFormRef.value.validate((isValidate: any, model: any, errors: any) => {
        if (isValidate) {
          if (!data.layTagItem.length) return layer.msg("请选择设备", { time: 1000 });
          let deviceName: any = [];
          data.layTagItem.forEach((items: any) => {
            if(data.systemType == '1') {
              deviceName.push(
                items.deviceNo + " —— " + items.deviceName + " —— " + items.model
              );
            } else {
              deviceName.push(
                items.managementNo + " —— " + items.deviceName + " —— " + items.model
              );
            }
          });
          let obj: any = {
            detectionId: data.detectionId, // 检测数据
            numberofTests: Number(data.validateModel.numberofTests),
            unit: data.validateModel.unit,
            deviceName: deviceName.join(","),
            tester: data.validateModel.testerId.join(","),
          };
          console.log("obj", obj);
          // visible.value = false;
          // layer.msg("认领成功", { time: 1000 });
          submitFrom(obj);
        }
      });
    };

    const submitFrom = async (obj: any) => {
      const res = await DoClaim(obj);
      if (res.code == 200) {
        visible.value = false;
        layer.msg("认领成功", { time: 1000 });
        event.emit("updata");

      }
    };

    // 清除校验
    const clearValidate = function () {
      layFormRef.value.clearValidate();
      visible.value = false;
    };

    // 重置表单
    const reset = function () {
      layFormRef.value.reset();
      //   data.validateModel.specialty = "1";
    };

    const getShebMsg = (item: any) => {
      data.msg = item;
      getShebeList();
    };

    const changeSelectTag = () => {
      if (data.validateModel.deviceNameIds && data.validateModel.deviceNameIds.length) {
        data.shebeiList.forEach((items: any) => {
          if (data.validateModel.deviceNameIds.includes(items.deviceId)) {
            data.sbTag.push(items);
          }
        });
      }
      getSbTag();
      console.log("validateModel.deviceNameIds", data.validateModel.deviceNameIds);
    };

    const getSbTag = () => {
      let newArr: any = [];
      let obj: any = {};
      for (var i = 0; i < data.sbTag.length; i++) {
        if (!obj[data.sbTag[i].deviceId]) {
          newArr.push(data.sbTag[i]);
          obj[data.sbTag[i].deviceId] = true;
        }
      }

      data.layTagItem = [...newArr];
    };

    const removerTag = (index: number) => {
      data.layTagItem.splice(index, 1);
      // data.sbTag.splice(index, 1);
      console.log('data.sbTag', data.sbTag);
    };

    return {
      open,
      visible,
      layFormRef,
      validate,
      clearValidate,
      reset,
      getShebMsg,
      changeSelectTag,
      getSbTag,
      removerTag,
      ...toRefs(data),
    };
  },
};
</script>
<style>
.layer_center .from_box {
  margin: 22px;
}

.layer_center .from_box .layui-select {
  width: 100%;
}

.layer_center .from_box .layui-cascader {
  width: 100%;
}
.danw {
  width: 100% !important;
}

.tagSb {
  margin-right: 6px;
  margin-bottom: 2px;
}
</style>
